import os

from flask import Blueprint, render_template, request, jsonify

from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from plugins.users.models.UserDep import UserDep

dir_path = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")

bp = Blueprint('users_dep', __name__, url_prefix='/dep')


# 用户组织结构首页
@bp.route('/')
@authorize('users:dep:index')
def index():
    return render_template('admin/dep/index.html')


@bp.route('/data', methods=['GET', 'POST'])
@authorize('users:dep:index')
def data():
    data = db.session.query(UserDep).all()
    rt = {}
    rt['data'] = []
    rt['status']= {}
    for d in data:
        rt['data'].append({
            'id': d.id,
            'pid': d.pid,
            'title': d.title,
            'status': d.status
        })
    rt['status']['code'] = 200
    rt['status']['message'] = '默认'
    return jsonify(rt)


@bp.route('/add', methods=['POST', 'GET'])
@authorize('users:dep:add')
def add():
    if request.method == 'POST':
        # 读取json数据
        data = request.get_json()

        dep = UserDep(
            id = data.get('id'),
            pid = data.get('pid'),
            title = str_escape(data.get('title')),
            sort = str_escape(data.get('sort')),
            status = str_escape(data.get('status'))
        )
        r = db.session.add(dep)
        db.session.commit()
        return success_api(msg='添加成功')
    else:
        return render_template('admin/dep/add.html')


@bp.route('/tree', methods=['POST', 'GET'])
@authorize('users:dep:index')
def tree():
    dep = UserDep.query.order_by(UserDep.sort).all()
    rtdata = []
    for d in dep:
        rtdata.append({
            'id': d.id,
            'title': d.title,
            'pid': d.pid,
            'status': d.status
        })
    rt = {
        'status': {'code': 200, 'message': '默认'},
        'data': rtdata
    }
    return jsonify(rt)

@bp.route('/edit', methods=['POST', 'GET'])
@authorize('users:dep:edit')
def edit():
    if request.method == 'POST':
        # 读取json数据
        data = request.get_json()
        id = data.get('id')
        data = {
            'pid': data.get('pid') or 0,
            'title': str_escape(data.get('title')),
            'sort': data.get('sort') or 0,
            'status': data.get('status')
        }
        d = UserDep.query.filter_by(id=id).update(data)
        if not d:
            return fail_api(msg='您要修改的记录不存在！')
        db.session.commit()
        return success_api(msg='修改成功')
    else:
        id = request.args.get('id')
        d = UserDep.query.get(id)
        print(d)
        return render_template('admin/dep/edit.html', d=d)

#删除
@bp.route('/remove', methods=['POST', 'GET'])
@authorize('users:dep:remove')
def remove():
    id = request.get_json().get('id')
    c = UserDep.query.filter_by(pid=id).count()
    if c > 0:
        return fail_api(msg='该部门下有子部门，无法删除！')
    d = UserDep.query.get(id)
    if d:
        db.session.delete(d)
        db.session.commit()
        return success_api(msg='删除成功')
    else:
        return fail_api(msg='您要删除的记录不存在！')

# 激活
@bp.route('/enable', methods=['POST'])
@authorize('users:dep:edit')
def enable():
    id = request.get_json().get('id')
    if id:
        d = UserDep.query.filter_by(id=id).update({'status': 1})
        if d:
            db.session.commit()
            return success_api(msg='激活成功')
        else:
            return fail_api(msg='激活失败。')
    else:
        return fail_api(msg='您要激活的记录不存在！')

# 禁用
@bp.route('/disable', methods=['POST'])
@authorize('users:dep:edit')
def disable():
    id = request.get_json().get('id')
    if id:
        d = UserDep.query.filter_by(id=id).update({'status': 0})
        if d:
            db.session.commit()
            return success_api(msg='禁用成功')
        else:
            return fail_api(msg='禁用失败。')
    else:
        return fail_api(msg='您要禁用的记录不存在！')